<template>
  <!-- eslint-disable no-unused-vars -->
  <div class="app-container">
    <el-card class="app-card apple-card">
      <div class="calendar-header">
        <div class="left-controls">
          <el-button type="default" @click="goToday" class="apple-button">今天</el-button>
          <el-button-group>
            <el-button type="default" @click="prevMonth" class="apple-button">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <el-button type="default" @click="nextMonth" class="apple-button">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
          <span class="date-title">{{ dateTitle }}</span>
        </div>
        <div class="right-controls">
          <el-select v-model="viewType" style="width: 120px;" class="apple-select">
            <el-option label="月" value="month" />
          </el-select>
          <el-button type="primary" @click="handleAdd" class="apple-button primary-button">
            <el-icon><Plus /></el-icon>添加值班工时
          </el-button>
        </div>
      </div>
      
      <!-- 自定义日历表格 -->
      <div class="custom-calendar-container" v-loading="loading">
        <table class="custom-calendar">
          <thead>
            <tr>
              <th v-for="day in weekDays" :key="day">{{ day }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(week, weekIndex) in calendarDays" :key="weekIndex">
              <td v-for="(day, dayIndex) in week" :key="`${weekIndex}-${dayIndex}`" 
                  :class="{ 'today': isToday(day.date), 'other-month': !day.currentMonth }">
                <div class="day-cell">
                  <div class="day-number">{{ day.dayOfMonth }}</div>
            
                  <!-- 值班记录显示区域 -->
                  <div class="duty-records" v-if="day.currentMonth">
                    <template v-if="hasDutyRecords(day.date)">
                      <div 
                        v-for="(record, idx) in getDutyRecords(day.date)" 
                        :key="idx"
                        class="duty-record"
                        :class="`duty-${getDutyTypeClass(record.duty_type)}`"
                        @click.stop="showDutyDetail(record)"
                      >
                        {{ record.duty_type }}
                      </div>
                    </template>
                    
                    <!-- 添加"添加工时"链接 -->
                    <div 
                      class="add-duty-link"
                      @click.stop="handleAddForDate(day.date)"
                    >
                      + 添加工时
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
            </div>
    </el-card>

    <!-- 添加/编辑工时记录弹窗 (复用工时填报的表单) -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="550px"
      append-to-body
      destroy-on-close
      custom-class="apple-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="员工" prop="nickname">
          <el-select v-model="form.nickname" placeholder="请选择员工" style="width: 100%" class="apple-select">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname || item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上线时间" prop="login_time">
          <el-date-picker
            v-model="form.login_time"
            type="datetime"
            placeholder="选择上线时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disableFutureDates"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="下线时间" prop="logout_time">
          <el-date-picker
            v-model="form.logout_time"
            type="datetime"
            placeholder="选择下线时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disableFutureDates"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="值班类型" prop="duty_type">
          <el-select v-model="form.duty_type" placeholder="请选择值班类型" style="width: 100%" class="apple-select">
            <el-option label="正常值班" value="正常值班" />
            <el-option label="临时值班" value="临时值班" />
          </el-select>
        </el-form-item>
        <el-form-item label="在线时长" prop="online_duration">
          <el-input v-model="form.online_duration" disabled class="apple-input">
            <template #append>小时</template>
          </el-input>
          <div class="form-tip">在线时长将根据上线和下线时间自动计算</div>
        </el-form-item>
        <el-form-item label="时薪" prop="hourly_wage">
          <el-input v-model="form.hourly_wage" disabled class="apple-input">
            <template #append>元/小时</template>
          </el-input>
          <div class="form-tip">时薪将根据在线时长自动计算（在线时长 × 5）</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="apple-button">取消</el-button>
        <el-button type="primary" @click="submitForm" class="apple-button primary-button">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ArrowLeft, ArrowRight, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAttendanceList, getAttendance, createAttendance, updateAttendance } from '@/api/attendance';
import { getServiceStaffList } from '@/api/user';
import { formatDate } from '@/utils/date';

defineOptions({
  name: 'DutyCalendarPage'
});

// 日历相关
const currentDate = ref(new Date());
const viewType = ref('month');
const dutyRecords = ref([]);
const loading = ref(false);
const userOptions = ref([]);

// 表单相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加值班工时');
const formRef = ref(null);
const form = reactive({
  nickname: null,
  login_time: '',
  logout_time: '',
  duty_type: '正常值班',
  online_duration: 0,
  hourly_wage: 0,
  duty_date: ''
});

// 计算日历标题
const dateTitle = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth() + 1;
  return `${year}-${month}`;
});

// 表单验证规则
const rules = {
  nickname: [{ required: true, message: '请选择员工', trigger: 'change' }],
  login_time: [{ required: true, message: '请选择上线时间', trigger: 'change' }],
  logout_time: [{ required: true, message: '请选择下线时间', trigger: 'change' }],
  duty_type: [{ required: true, message: '请选择值班类型', trigger: 'change' }]
};

// 星期标题
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 当前月份的日历数据
const calendarDays = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  
  // 获取当月第一天
  const firstDay = new Date(year, month, 1);
  // 获取当月第一天是星期几
  const firstDayOfWeek = firstDay.getDay(); 
  
  // 获取当月天数
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  
  // 获取上月天数
  const daysInPrevMonth = new Date(year, month, 0).getDate();
  
  // 初始化日历数组 (6周 x 7天)
  const days = [];
  let dayCounter = 1;
  let nextMonthCounter = 1;
  
  // 填充6行日历
  for (let week = 0; week < 6; week++) {
    const weekDays = [];
    
    for (let day = 0; day < 7; day++) {
      if (week === 0 && day < firstDayOfWeek) {
        // 上月日期
        const prevMonthDay = daysInPrevMonth - (firstDayOfWeek - day - 1);
        const date = new Date(year, month - 1, prevMonthDay);
        weekDays.push({
          date: formatDate(date, 'YYYY-MM-DD'),
          dayOfMonth: prevMonthDay,
          currentMonth: false
        });
      } else if (dayCounter <= daysInMonth) {
        // 当月日期
        const date = new Date(year, month, dayCounter);
        weekDays.push({
          date: formatDate(date, 'YYYY-MM-DD'),
          dayOfMonth: dayCounter,
          currentMonth: true
        });
        dayCounter++;
      } else {
        // 下月日期
        const date = new Date(year, month + 1, nextMonthCounter);
        weekDays.push({
          date: formatDate(date, 'YYYY-MM-DD'),
          dayOfMonth: nextMonthCounter,
          currentMonth: false
        });
        nextMonthCounter++;
      }
    }
    
    days.push(weekDays);
    
    // 如果最后一行都是下月的日期，不再添加新行
    if (dayCounter > daysInMonth && week >= 4) break;
  }
  
  return days;
});

// 将值班记录按日期分组
const dutyRecordsByDate = computed(() => {
  const recordMap = {};
  
  if (!dutyRecords.value || dutyRecords.value.length === 0) {
    return recordMap;
  }
  
  dutyRecords.value.forEach(record => {
    if (!record) return;
    
    // 获取日期字符串（YYYY-MM-DD格式）
    let dateStr = '';
    try {
      if (record.duty_date) {
        dateStr = typeof record.duty_date === 'string' 
          ? record.duty_date.split('T')[0] 
          : formatDate(new Date(record.duty_date), 'YYYY-MM-DD');
      } else if (record.login_time) {
        dateStr = typeof record.login_time === 'string'
          ? record.login_time.split('T')[0]
          : formatDate(new Date(record.login_time), 'YYYY-MM-DD');
      } else {
        return;
      }
    } catch (e) {
      console.error('日期处理错误:', e);
      return;
    }
    
    if (!recordMap[dateStr]) {
      recordMap[dateStr] = [];
    }
    recordMap[dateStr].push({
      ...record,
      nicknameDisplay: record.nickname_display || '未知用户'
    });
  });
  
  return recordMap;
});

// 判断某日期是否有值班记录
const hasDutyRecords = (dateStr) => {
  return dutyRecordsByDate.value[dateStr] && dutyRecordsByDate.value[dateStr].length > 0;
};

// 获取某日期的值班记录
const getDutyRecords = (dateStr) => {
  return dutyRecordsByDate.value[dateStr] || [];
};

// 获取值班类型对应的样式类
const getDutyTypeClass = (dutyType) => {
  const map = {
    '正常值班': 'normal',
    '临时值班': 'temp',
  };
  return map[dutyType] || 'normal';
};

// 判断是否为今天
const isToday = (dateStr) => {
  const today = formatDate(new Date(), 'YYYY-MM-DD');
  return dateStr === today;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '暂无数据';
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) {
      // 日期无效，尝试其他格式
      console.warn('日期格式无效:', dateTimeStr);
      return dateTimeStr;
    }
    
    // 格式化为 YYYY-MM-DD HH:MM:SS
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateTimeStr || '格式错误';
  }
};

// 显示值班详情
const showDutyDetail = (record) => {
  // 确保记录数据有效
  if (!record) {
    ElMessage.warning('无法显示详情：记录数据无效');
    return;
  }
  
  // 处理不同格式的记录数据
  const employeeName = record.nicknameDisplay || record.nickname_display || '未知用户';
  
  // 构建详情内容
  const detailContent = `
    <div class="duty-detail">
      <p><strong>员工：</strong>${employeeName}</p>
      <p><strong>值班类型：</strong><span class="duty-type duty-${getDutyTypeClass(record.duty_type)}">${record.duty_type}</span></p>
      <p><strong>上线时间：</strong>${formatDateTime(record.login_time)}</p>
      <p><strong>下线时间：</strong>${formatDateTime(record.logout_time)}</p>
      <p><strong>在线时长：</strong>${record.online_duration} 小时</p>
      <p><strong>时薪：</strong>${record.hourly_wage} 元/小时</p>
    </div>
  `;
  
  // 显示详情对话框
  ElMessageBox.alert(detailContent, '值班详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭',
    callback: () => {
      // 显示操作按钮
      ElMessageBox.confirm('您想对此记录进行操作吗？', '操作选择', {
        confirmButtonText: '编辑',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 编辑该记录
        handleEdit(record);
      }).catch(() => {
        // 取消操作
      });
    }
  });
};

// 初始化
onMounted(() => {
  console.log('DutyCalendar组件挂载，初始化日期:', formatDate(currentDate.value, 'YYYY-MM-DD'));
  loadDutyRecords();
  loadUserOptions();
});

// 监听日期变化
watch(currentDate, (newDate) => {
  console.log('日期变化，准备加载数据:', formatDate(newDate, 'YYYY-MM-DD'));
    loadDutyRecords();
}, { immediate: true });

// 监听上线时间和下线时间变化，自动计算在线时长和时薪
watch([() => form.login_time, () => form.logout_time], ([newLoginTime, newLogoutTime]) => {
  if (newLoginTime && newLogoutTime) {
    // 计算时间差（小时）
    const loginTimestamp = new Date(newLoginTime).getTime();
    const logoutTimestamp = new Date(newLogoutTime).getTime();
    
    // 检查日期是否为同一天 - 移除实时警告
    const loginDate = new Date(newLoginTime).toISOString().split('T')[0];
    const logoutDate = new Date(newLogoutTime).toISOString().split('T')[0];
    
    // 只在下线时间晚于上线时间时计算时长
    if (logoutTimestamp <= loginTimestamp) {
      ElMessage.warning('下线时间必须晚于上线时间');
      return;
    }
    
    // 更精确的时间计算（保留一位小数）
    const durationHours = (logoutTimestamp - loginTimestamp) / (1000 * 60 * 60);
    form.online_duration = parseFloat(durationHours.toFixed(1));
    
    // 时薪计算（保留一位小数）
    form.hourly_wage = parseFloat((form.online_duration * 5).toFixed(1));
    
    // 自动设置值班日期
    if (!form.duty_date) {
      form.duty_date = loginDate;
    }
  }
}, { deep: true });

// 单独监听上线时间的变化，自动更新下线时间为同一天
watch(() => form.login_time, (newLoginTime) => {
  if (newLoginTime) {
    const loginDate = new Date(newLoginTime);
    const loginDateStr = loginDate.toISOString().split('T')[0];
    
    // 检查下线时间是否为空或者不是同一天，都需要更新
    if (!form.logout_time || (form.logout_time && new Date(form.logout_time).toISOString().split('T')[0] !== loginDateStr)) {
      // 创建新的下线时间（同一天的15:00）
      const newLogoutTime = new Date(loginDate);
      // 判断当前上线时间的小时数
      const loginHours = loginDate.getHours();
      
      // 如果上线时间已经晚于13:00，则设置下线时间为上线时间后2小时
      if (loginHours >= 13) {
        newLogoutTime.setHours(loginHours + 2, loginDate.getMinutes(), 0, 0);
      } else {
        // 否则，设置为当天15:00
        newLogoutTime.setHours(15, 0, 0, 0);
      }
      
      // 确保下线时间晚于上线时间
      if (newLogoutTime.getTime() <= loginDate.getTime()) {
        newLogoutTime.setTime(loginDate.getTime() + 2 * 60 * 60 * 1000); // 加2小时
      }
      
      // 更新表单中的下线时间
      form.logout_time = newLogoutTime.toISOString().slice(0, 19);
      console.log('自动更新下线时间为:', form.logout_time);
    }
  }
});

// 日历导航方法
const goToday = () => {
  currentDate.value = new Date();
};

const prevMonth = () => {
  const date = new Date(currentDate.value);
  date.setMonth(date.getMonth() - 1);
  currentDate.value = date;
};

const nextMonth = () => {
  const date = new Date(currentDate.value);
  date.setMonth(date.getMonth() + 1);
  currentDate.value = date;
};

// 获取当前月份的值班记录
const loadDutyRecords = async () => {
  loading.value = true;
  try {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth() + 1; // 月份从0开始，需要+1
    
    // 构建查询日期范围
    const firstDay = new Date(year, month - 1, 1);
    const lastDay = new Date(year, month, 0); // 当前月的最后一天
    
    const startDate = formatDate(firstDay, 'YYYY-MM-DD');
    const endDate = formatDate(lastDay, 'YYYY-MM-DD');
    
    console.log('加载日期范围:', startDate, '到', endDate);
    
    const response = await getAttendanceList({
      duty_date_start: startDate,
      duty_date_end: endDate,
      page_size: 1000 // 确保获取足够多的记录
    });
    
    console.log('API返回的原始数据:', response);
    
    // 检查响应数据结构
    let records = [];
    if (response && response.results) {
      records = response.results;
    } else if (response && response.data && response.data.results) {
      records = response.data.results;
    } else if (Array.isArray(response)) {
      records = response;
    }
    
    dutyRecords.value = records;
    console.log(`加载到值班记录数量: ${dutyRecords.value.length}`);
    
  } catch (error) {
    console.error('加载值班记录失败', error);
    ElMessage.error('加载值班记录失败');
    dutyRecords.value = []; // 清空记录，不使用测试数据
  } finally {
    loading.value = false;
  }
};

// 获取用户选项
const loadUserOptions = async () => {
  try {
    console.log('开始加载用户选项...');
    const response = await getServiceStaffList();
    console.log('获取到用户API响应:', response);
    
    // 添加默认模拟数据，确保选项列表不为空
    userOptions.value = [
      { id: 1, nickname: '默认客服1' },
      { id: 2, nickname: '默认客服2' },
      { id: 3, nickname: '默认客服3' }
    ];
    
    // 尝试从API响应中提取数据
    if (response) {
      let userData = [];
      
      // 处理不同的响应格式
      if (response.data && Array.isArray(response.data)) {
        userData = response.data;
        console.log('使用response.data数组格式');
      } else if (response.data && response.data.items && Array.isArray(response.data.items)) {
        userData = response.data.items;
        console.log('使用response.data.items数组格式');
      } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
        userData = response.data.results;
        console.log('使用response.data.results数组格式');
      } else if (response.results && Array.isArray(response.results)) {
        userData = response.results;
        console.log('使用response.results数组格式');
      } else if (Array.isArray(response)) {
        userData = response;
        console.log('使用直接数组响应格式');
      }
      
      // 如果获取到有效数据，则替换默认数据
      if (userData && userData.length > 0) {
        userOptions.value = userData.map(user => ({
          id: user.id,
          nickname: user.nickname || user.username || `员工${user.id}`
        }));
        console.log('成功格式化用户选项:', userOptions.value);
      } else {
        console.warn('API返回的用户数据为空或格式不正确，使用默认数据');
      }
    }
  } catch (error) {
    console.error('加载用户选项失败:', error);
    // 保留默认数据作为备用
    ElMessage.warning('加载员工列表失败，使用默认数据');
  }
};

// 处理添加值班记录
const handleAdd = () => {
  dialogTitle.value = '添加值班工时';
  resetForm();
  
  // 设置默认上线时间为当天的9:00
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 重置时间部分
  const localDate = today.toISOString().split('T')[0]; // 获取本地日期字符串
  
  // 设置特定时间并处理时区
  form.login_time = `${localDate}T09:00:00`;
  form.logout_time = `${localDate}T15:00:00`;
  
  // 设置duty_date为当天
  form.duty_date = localDate;
  
  console.log('设置默认时间:', {
    上线时间: form.login_time,
    下线时间: form.logout_time,
    值班日期: form.duty_date
  });
  
  dialogVisible.value = true;
};

// 处理编辑值班记录
const handleEdit = async (duty) => {
  dialogTitle.value = '编辑值班工时';
  resetForm();
  
  try {
    console.log('获取详情，ID:', duty.id);
    const response = await getAttendance(duty.id);
    console.log('获取到详情:', response);
    
    // 确定响应数据格式
    const data = response.data ? response.data : response;
    
    if (data) {
      // 处理员工数据
      let employeeId = data.nickname;
      
      // 检查员工是否存在于当前选项中
      const matchingEmployee = userOptions.value.find(user => user.id === employeeId);
      if (!matchingEmployee && data.nickname_display) {
        // 如果没有找到匹配的员工但有显示名称，添加到选项中
        userOptions.value.push({
          id: employeeId,
          nickname: data.nickname_display
        });
      }
    
    Object.assign(form, {
        id: data.id,
        nickname: employeeId,
        login_time: data.login_time,
        logout_time: data.logout_time,
        duty_type: data.duty_type,
        online_duration: data.online_duration,
        hourly_wage: data.hourly_wage,
        duty_date: data.duty_date
    });
      
    dialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取值班记录详情失败', error);
    ElMessage.error('获取值班记录详情失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 检查上线时间和下线时间是否在同一天
        if (form.login_time && form.logout_time) {
          const loginDate = new Date(form.login_time).toISOString().split('T')[0];
          const logoutDate = new Date(form.logout_time).toISOString().split('T')[0];
          
          if (loginDate !== logoutDate) {
            ElMessage.error('上线时间和下线时间必须在同一天');
            return;
          }
        }
        
        // 确保duty_date字段已设置
        if (!form.duty_date && form.login_time) {
          const loginDate = new Date(form.login_time).toISOString().split('T')[0];
          form.duty_date = loginDate;
          console.log('自动设置duty_date为:', form.duty_date);
        }
        
        // 准备提交数据
        const submitData = { ...form };
        
        // 如果nickname是一个对象(使用默认数据时可能出现)，转换为ID
        if (typeof submitData.nickname === 'object' && submitData.nickname !== null) {
          submitData.nickname = submitData.nickname.id;
        }
        
        console.log('准备提交数据:', submitData);
        
        let response;
        if (form.id) {
          response = await updateAttendance(form.id, submitData);
          ElMessage.success('更新成功');
        } else {
          response = await createAttendance(submitData);
          ElMessage.success('添加成功');
        }
        dialogVisible.value = false;
        
        console.log('添加/更新记录成功，响应:', response);
        
        // 延迟重新加载数据
        setTimeout(() => {
          console.log('重新加载数据...');
          loadDutyRecords();
        }, 1000);
      } catch (error) {
        console.error('提交表单失败', error);
        if (error.response && error.response.data) {
          // 详细显示错误信息
          const errorDetail = error.response.data.detail || 
                              JSON.stringify(error.response.data);
          ElMessage.error(`操作失败: ${errorDetail}`);
        } else {
          ElMessage.error('操作失败');
        }
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.nickname = null;
  form.login_time = '';
  form.logout_time = '';
  form.duty_type = '正常值班';
  form.online_duration = 0;
  form.hourly_wage = 0;
  form.duty_date = '';
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 禁用未来日期
const disableFutureDates = (date) => {
  return date > new Date();
};

// 为特定日期添加值班记录
const handleAddForDate = (dateStr) => {
  dialogTitle.value = '添加值班工时';
  resetForm();
  
  // 直接使用日期字符串设置时间
  form.login_time = `${dateStr}T09:00:00`;
  form.logout_time = `${dateStr}T15:00:00`;
  
  // 设置duty_date为选中的日期
  form.duty_date = dateStr;
  
  console.log('为指定日期设置默认值:', {
    日期: dateStr,
    上线时间: form.login_time,
    下线时间: form.logout_time,
    值班日期: form.duty_date
  });
  
  dialogVisible.value = true;
};
</script>

<style scoped>
/* 自定义日历样式 */
.custom-calendar-container {
  margin-top: 20px;
}

.custom-calendar {
  width: 100%;
  border-collapse: separate;
  border-spacing: 4px;
}

.custom-calendar th {
  padding: 10px;
  text-align: center;
  font-weight: 600;
  background-color: #f5f7fa;
  border-radius: 8px;
      }
      
.custom-calendar td {
  height: 120px;
  vertical-align: top;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.custom-calendar td:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.custom-calendar td.today {
  background-color: #f0f7ff;
}

.custom-calendar td.other-month {
  opacity: 0.5;
}

.day-cell {
  position: relative;
  height: 100%;
  padding: 6px;
  display: flex;
  flex-direction: column;
}

.day-number {
  font-weight: 600;
  padding: 4px;
  text-align: right;
}

.duty-records {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 6px;
}

.duty-record {
  padding: 8px 10px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.duty-record:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 不同值班类型的样式 */
.duty-normal {
  background-color: #ecf8f0;
  border-left: 3px solid #34c759;
  color: #155724;
}

.duty-temp {
  background-color: #fff6e9;
  border-left: 3px solid #ff9500;
  color: #865514;
}

.duty-family {
  background-color: #edf4ff;
  border-left: 3px solid #0071e3;
  color: #0056b3;
}

.duty-pushu {
  background-color: #feeeef;
  border-left: 3px solid #ff3b30;
  color: #cc2f29;
}

/* 添加工时链接样式 */
.add-duty-link {
  margin-top: 8px;
  padding: 6px 8px;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  background-color: #f0f7ff;
  color: #0071e3;
  border: 1px dashed #0071e3;
  transition: all 0.2s ease;
}

.add-duty-link:hover {
  background-color: #e0f0ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-title {
  font-size: 18px;
  font-weight: 600;
  margin-left: 12px;
  color: #333;
}

.duty-detail {
  line-height: 1.8;
  font-size: 14px;
  padding: 8px 0;
}

.duty-detail .duty-type {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: normal;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  padding-top: 6px;
}

/* 苹果风格卡片 */
.apple-card {
  border-radius: 12px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 4px 8px rgba(0, 0, 0, 0.03) !important;
  transition: box-shadow 0.3s ease, transform 0.2s ease;
  margin-bottom: 20px;
  border: none !important;
  overflow: hidden;
}

.apple-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 8px 16px rgba(0, 0, 0, 0.06) !important;
}

/* 苹果风格按钮 */
.apple-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: background-color 0.3s, transform 0.1s, box-shadow 0.3s !important;
  border: none !important;
  padding: 10px 16px !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08) !important;
}

.apple-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12) !important;
}

.apple-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

.primary-button {
  background-color: #0071e3 !important;
  color: white !important;
}

.primary-button:hover {
  background-color: #0077ed !important;
}

/* 苹果风格选择器 */
.apple-select .el-input__wrapper {
  border-radius: 8px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
}

.apple-select .el-input__wrapper:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-select .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 苹果风格日期选择器 */
.apple-date-picker .el-input__wrapper {
  border-radius: 8px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
}

.apple-date-picker .el-input__wrapper:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-date-picker .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 苹果风格输入框 */
.apple-input .el-input__wrapper {
  border-radius: 8px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  padding: 4px 12px !important;
  transition: box-shadow 0.3s ease !important;
}

.apple-input .el-input__wrapper:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.apple-input .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.3) !important;
}

/* 添加日历容器样式 */
.calendar-container {
  position: relative;
  min-height: 600px;
}
</style>

<!-- 添加全局样式 -->
<style>
/* 苹果风格对话框 */
.apple-dialog {
  border-radius: 12px !important;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15), 0 5px 15px rgba(0, 0, 0, 0.08) !important;
}

.apple-dialog .el-dialog__header {
  padding: 16px 20px !important;
  margin: 0 !important;
  border-bottom: 1px solid #f0f0f0 !important;
  background-color: #f5f7fa !important;
}

.apple-dialog .el-dialog__title {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #333 !important;
}

.apple-dialog .el-dialog__body {
  padding: 20px !important;
}

.apple-dialog .el-dialog__footer {
  padding: 12px 20px 16px !important;
  border-top: 1px solid #f0f0f0 !important;
}

.apple-dialog .el-dialog__headerbtn {
  top: 16px !important;
  right: 16px !important;
}

.apple-dialog .el-dialog__headerbtn:hover .el-dialog__close {
  color: #0071e3 !important;
}

/* 苹果风格消息框样式 */
.el-message-box {
  border-radius: 12px !important;
  overflow: hidden !important;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15), 0 5px 15px rgba(0, 0, 0, 0.08) !important;
}

.el-message-box__header {
  padding: 16px 20px !important;
  background-color: #f5f7fa !important;
  border-bottom: 1px solid #f0f0f0 !important;
}

.el-message-box__title {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #333 !important;
}

.el-message-box__content {
  padding: 20px !important;
  color: #333 !important;
}

.el-message-box__btns {
  padding: 12px 20px 16px !important;
  border-top: 1px solid #f0f0f0 !important;
}

.el-message-box__btns .el-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: all 0.3s !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08) !important;
}

.el-message-box__btns .el-button--primary {
  background-color: #0071e3 !important;
  border-color: #0071e3 !important;
  color: white !important;
}

.el-message-box__btns .el-button--primary:hover {
  background-color: #0077ed !important;
  border-color: #0077ed !important;
}

/* 值班类型标签样式 */
.el-message-box .duty-type {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 4px;
}

.el-message-box .duty-normal {
  background-color: #ecf8f0;
  border-left: 3px solid #34c759;
}

.el-message-box .duty-temp {
  background-color: #fff6e9;
  border-left: 3px solid #ff9500;
}

.el-message-box .duty-family {
  background-color: #edf4ff;
  border-left: 3px solid #0071e3;
}

.el-message-box .duty-pushu {
  background-color: #feeeef;
  border-left: 3px solid #ff3b30;
}
</style> 